<?php
/**
 * Created by PhpStorm.
 * User: Egg
 * Date: 2018/3/19
 * Time: 14:18
 */

namespace Home\Controller;


use Common\Common\HttpUtil;
use Home\Model\UserAuthLogic;
use Think\Controller;
use Wechat\Model\WxLogic;

class UserAuthController extends Controller\RestController
{
    /**
     * 显示注册页面
     */
    public function register()
    {
        /**
         * code 是微信静默授权后给识别码
         * 需要再次提交给微信换取 openid
         */
        $code = $_GET['code'];
        session('code', $code);
        $this->display('./index');
    }

    /**
     * 显示销售员认证页面
     */
    public function saleAuthShow()
    {
        /**
         * 在session中保存销售员的 id
         */
        $sid = $_GET['sid'];
        session('sid', $sid);
        $this->display('./submit_saler');
    }

    /**
     * 导购员注册
     */
    public function registerGuide()
    {
        /**
         * 微信静默授权通过 code 换取 openid 的地址
         */
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . C('appid') .
            '&secret=' . C('appsecret') .
            '&code=' . session('code') .
            '&grant_type=authorization_code';
        $result = HttpUtil::https_request($url);
        $userInfo = json_decode($result);
        //提取json中的openid
        $openid = $userInfo->openid;
        if (empty($openid)) {
            $this->error('请从微信入口进入');
            exit;
        }
        //将openid缓存在session里
        session('openid', $openid);

        $model = D('wx_users');
        //判断用户是否存在
        $dbUser = $model->getByOpenid($openid);
        if (empty($dbUser)) {
            //当用户不存在时 添加用户的openid
            $data['openid'] = $openid;
            $model->data($data)->add();
        }

        $tel = I('tel');
        //判读对应销售商
        $distributerInfo = $model->getByTel($tel);
        if (empty($distributerInfo)) {
            $this->error('该经销商不存在');
            return;
        }
        /*
         * 再次取出用户数据
         * 二次判断用户是否存在
         */
        $saleInfo = $model->getByOpenid($openid);
        if (empty($saleInfo)) {
            $this->error('信息无法提交,请重试！');
            return;
        }
        $wxLogic = new WxLogic();
        $userAuthLogic = new UserAuthLogic();

        $tplData = $userAuthLogic->createSalerTemplateData($distributerInfo['openid'], $saleInfo);
        $wxLogic->sendTemplateMsgs($tplData);
        $this->success('申请成功');
    }

    /**
     *  销售商审核导购员
     */
    public function saleAuth()
    {
        //从 session 中获取到导购员 id
        $sid = session('sid');
//        session('sid', null);
        if (empty($sid)) {
            $this->error('导购员不存在,请联系导购员重新提交');
            exit;
        }
        $wxLogic = new WxLogic();
        $userAuthLogic = new UserAuthLogic();
        //获取提交的导购员openid
        $openid = $userAuthLogic->getOpenid($sid);
        //生成审核成功模板并发送
        $tplData = $userAuthLogic->createAuthTemplateData($openid);
        $wxLogic->sendTemplateMsgs($tplData);
    }

}
